package com.taormina.searchservice;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jdom.JDOMException;
import org.springframework.stereotype.Component;

@Component("searchService")
public class YahooSearchServiceImpl extends HttpPostSearchService {

	private static final String SEARCH_URL = "http://search.yahoo.com/search";
	private static final String QUERY_PREFIX = "p";
	private static final Pattern LINK_ELEMENT_PATTERN = Pattern.compile("<h3><a[^>]*");
	private static final Pattern LINK_HREF_PATTERN = Pattern.compile("http[^\"]*");
	
	@Override
	protected String getSearchUrl() {
		return SEARCH_URL;
	}
	
	@Override
	protected String getQueryPrefix() {
		return QUERY_PREFIX;
	}

	@Override
	List<String> getTopSearchLinks(File xhtmlMarkup) throws IOException {
		
		String markupText = fileToString(xhtmlMarkup);
		
		List<String> links = new ArrayList<String>();
		
		Matcher elementMatcher = LINK_ELEMENT_PATTERN.matcher(markupText);
		
		while (elementMatcher.find() && links.size() < MAX_RESULTS) {
			Matcher linkMatcher = LINK_HREF_PATTERN.matcher(elementMatcher.group());
			if (linkMatcher.find()) {
				links.add(URLDecoder.decode(linkMatcher.group(), "UTF-8"));
			}
		}
		
		return links;
	}
	
	@Override
	protected File launderMarkup(InputStream messyMarkup) throws JDOMException, IOException {
		File markupFile = super.launderMarkup(messyMarkup);
		String markupText = fileToString(markupFile);
		markupFile.delete();

		markupText = markupText.replaceAll("<style [^<]*</style>", "");
		
		File tempFile = File.createTempFile("tmp", null);
		FileWriter writer = new FileWriter(tempFile);
		writer.write(markupText);
		writer.close();
		
		return tempFile;
	}

}
